﻿using DeviceMaintainGIS.Entity;
using DeviceMaintainGIS.Model.Document;
using DeviceMaintainGIS.Model.Enum;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;

namespace AchieveManageWeb.Controllers
{
    public class DocumentController : Controller
    {
        //
        // GET: /Document/
        /// <summary>
        /// 资料列表页
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            return View();
        }
        /// <summary>
        /// 资料添加页
        /// </summary>
        /// <returns></returns>
        public ActionResult DocumentAdd()
        {
            ViewBag.DocumentTypeModelList = GetDocumentType();
            return View();
        }
        /// <summary>
        /// 资料编辑页
        /// </summary>
        /// <returns></returns>
        public ActionResult DocumentEdit()
        {
            ViewBag.DocumentTypeModelList = GetDocumentType();

            DocumentModel lin = new DocumentModel();
            string DocumentId = Request["DocumentId"];

            using (CYOADBEntities Entities = new CYOADBEntities())
            {
                var linqs = from a in Entities.Document_Tab.Where(i => i.DocumentId == DocumentId)
                            select new DocumentModel
                            {
                                DocumentId = a.DocumentId,
                                DocumentName = a.DocumentName,
                                DocumentTypeId = a.DocumentTypeId,
                                Path = a.Path,
                                IsSecrecy = a.IsSecrecy == true ? "是" : "否",
                            };
                lin = linqs.FirstOrDefault();
            };

            return View(lin);
        }
        /// <summary>
        /// 资料关系添加页
        /// </summary>
        /// <returns></returns>
        public ActionResult DocumentRelationAdd()
        {
            DocumentModel lin = new DocumentModel();
            using (CYOADBEntities Entities = new CYOADBEntities())
            {
                string DocumentId = Request["DocumentId"];
                var linqs = from a in Entities.Document_Tab.Where(i => i.DocumentId == DocumentId)
                            select new DocumentModel
                            {
                                DocumentId = a.DocumentId,
                                DocumentName = a.DocumentName,
                                DocumentTypeId = a.DocumentTypeId,
                                Path = a.Path,
                                IsSecrecy = a.IsSecrecy == true ? "是" : "否",
                            };
                lin = linqs.FirstOrDefault();
            }
            return View(lin);
        }
        /// <summary>
        /// 获取资料类型信息
        /// </summary>
        /// <returns></returns>
        public List<DocumentTypeModel> GetDocumentType()
        {
            using (CYOADBEntities Entities = new CYOADBEntities())
            {
                var linq = from a in Entities.DocumentType_Tab
                           select new DocumentTypeModel
                           {
                               DocumentTypeId = a.DocumentTypeId,
                               DocumentType = a.DocumentType,

                           };
                List<DocumentTypeModel> SelDevInfoModelList = linq.ToList();
                return SelDevInfoModelList;
            }

        }
        /// <summary>
        /// 根据条件查询资料信息
        /// </summary>
        /// <returns></returns>
        public ActionResult GetAllDocumentList()
        {
            //首先获取前台传递过来的参数
            int pageindex = Request["page"] == null ? 1 : Convert.ToInt32(Request["page"]);
            int pagesize = Request["rows"] == null ? 10 : Convert.ToInt32(Request["rows"]);

            string selDocumentName = Request["selDocumentName"] == null ? "" : Request["selDocumentName"].ToString();
            string strJson;
            int totalCount;   //输出参数
            using (CYOADBEntities Entities = new CYOADBEntities())
            {

                var linq = from a in Entities.Document_Tab
                           join m in Entities.DocumentType_Tab on a.DocumentTypeId equals m.DocumentTypeId
                            into tmpDocumentType
                           let s = tmpDocumentType.FirstOrDefault()
                           select new DocumentModel
                           {
                               DocumentId = a.DocumentId,
                               DocumentName = a.DocumentName,
                               DocumentTypeName = s.DocumentType,
                               IsSecrecy = a.IsSecrecy == true ? "是" : "否",
                               Path = a.Path,
                               AddTime = a.AddTime,
                               DownloadUrl = a.DownloadUrl
                           };


                //设备名称
                if (!string.IsNullOrEmpty(selDocumentName))
                {
                    linq = linq.Where(i => i.DocumentName.Contains(selDocumentName));
                }

                totalCount = linq.Count();
                List<DocumentModel> list = linq.OrderByDescending(i => i.AddTime).Take(pagesize * pageindex).Skip(pagesize * (pageindex - 1)).ToList();

                JavaScriptSerializer jsonSerialize = new JavaScriptSerializer();
                strJson = jsonSerialize.Serialize(list);
            }

            var jsonResult = new { total = totalCount.ToString(), rows = strJson };
            return Content("{\"total\": " + totalCount.ToString() + ",\"rows\":" + strJson + "}");
        }
        /// <summary>
        /// 资料添加
        /// </summary>
        /// <returns></returns>
        public ActionResult DocumentInfoAdd(DocumentModel dm)
        {
            int code = 0;
            string newID = Guid.NewGuid().ToString();
            Document_Tab dt = new Document_Tab();
            dt.DocumentId = newID;
            dt.DocumentTypeId = dm.DocumentTypeId;
            dt.DocumentName = dm.DocumentName;
            dt.Path = dm.Path;
            dt.AddTime = System.DateTime.Now;
            dt.DownloadUrl = dm.DownloadUrl;
            if (dm.IsSecrecy == "1")
            {
                dt.IsSecrecy = true;
            }
            else
            {
                dt.IsSecrecy = false;

            }
            using (CYOADBEntities Entities = new CYOADBEntities())
            {

                int Count = Entities.Document_Tab.Where(i => i.DocumentName == dm.DocumentName).Count();
                if (Count > 0)
                {
                    return Content("{\"msg\":\"添加失败！资料名称已存在！\",\"success\":false}");
                }

                Entities.Document_Tab.Add(dt);
                Entities.Entry<Document_Tab>(dt).State = System.Data.Entity.EntityState.Added;
                code = Entities.SaveChanges();
                if (code > 0)
                {
                    return Content("{\"msg\":\"添加成功！\",\"success\":true}");
                }
                else
                {
                    return Content("{\"msg\":\"添加失败！入库失败\",\"success\":false}");
                }
            }
        }

        /// <summary>
        /// 资料编辑
        /// </summary>
        /// <param name="dm"></param>
        /// <returns></returns>
        public ActionResult DocumentInfoEdit(DocumentModel dm)
        {
            int code = 0;
            using (CYOADBEntities Entities = new CYOADBEntities())
            {
                //获取当前设备的关系信息
                Document_Tab dt = Entities.Document_Tab.Where(i => i.DocumentId == dm.DocumentId).FirstOrDefault();
                dt.DocumentTypeId = dm.DocumentTypeId;
                dt.DocumentName = dm.DocumentName;
                dt.Path = dm.Path;
                dt.DownloadUrl = dm.DownloadUrl;
                if (dm.IsSecrecy == "1")
                {
                    dt.IsSecrecy = true;
                }
                else
                {
                    dt.IsSecrecy = false;

                }
                int Count = Entities.Document_Tab.Where(i => i.DocumentName == dm.DocumentName).Count();
                if (Count > 1)
                {
                    return Content("{\"msg\":\"保存失败！资料名称已存在！\",\"success\":false}");
                }

                Entities.Document_Tab.Add(dt);
                Entities.Entry<Document_Tab>(dt).State = System.Data.Entity.EntityState.Modified;
                code = Entities.SaveChanges();
                if (code > 0)
                {
                    return Content("{\"msg\":\"保存成功！\",\"success\":true}");
                }
                else
                {
                    return Content("{\"msg\":\"保存失败！入库失败\",\"success\":false}");
                }
            }
        }

        /// <summary>
        /// 删除资料
        /// </summary>
        /// <param name="DocumentId"></param>
        /// <returns></returns>
        public ActionResult DocumentDel()
        {
            string DocumentId = Request["DocumentId"] == null ? "1" : Request["DocumentId"].ToString();
            int Code = 0;
            using (CYOADBEntities Entities = new CYOADBEntities())
            {
                Document_Tab dt = Entities.Document_Tab.Where(i => i.DocumentId == DocumentId).FirstOrDefault();
                Entities.Document_Tab.Add(dt);
                Entities.Entry<Document_Tab>(dt).State = System.Data.Entity.EntityState.Deleted;

                DocumentRelation_Tab DocumentRelationTab = Entities.DocumentRelation_Tab.Where(i => i.DocumentId == DocumentId).FirstOrDefault();
                if (DocumentRelationTab != null)
                {
                    Entities.DocumentRelation_Tab.Add(DocumentRelationTab);
                    Entities.Entry<DocumentRelation_Tab>(DocumentRelationTab).State = System.Data.Entity.EntityState.Deleted;
                }
                Code = Entities.SaveChanges();

                if (Code > 0)
                {

                    if (System.IO.File.Exists(dt.Path))
                    {
                        //参数1：要删除的文件路径
                        System.IO.File.Delete(dt.Path);
                    }
                    return Content("{\"msg\":\"删除成功！\",\"success\":true}");
                }
                else
                {
                    return Content("{\"msg\":\"删除失败！\",\"success\":true}");
                }
            }
        }

        /// <summary>
        /// 获取关系信息
        /// </summary>
        /// <returns></returns>
        public ActionResult GetDocumentRelation()
        {
            //首先获取前台传递过来的参数
            int pageindex = Request["page"] == null ? 1 : Convert.ToInt32(Request["page"]);
            int pagesize = Request["rows"] == null ? 10 : Convert.ToInt32(Request["rows"]);

            string DocumentId = Request["DocumentId"] == null ? "" : Request["DocumentId"].ToString();
            string strJson;
            int totalCount;   //输出参数
            using (CYOADBEntities Entities = new CYOADBEntities())
            {
                var linq = from a in Entities.DocumentRelation_Tab.Where(i => i.DocumentId == DocumentId)
                           join d in Entities.DevInfo_Tab on a.LPDId equals d.DeviceId
                           into tmpDevInfo
                           let Dev = tmpDevInfo.FirstOrDefault()
                           join p in Entities.ProInfo_Tab on a.LPDId equals p.ProjectId
                           into tmpProInfo
                           let Pro = tmpProInfo.FirstOrDefault()
                           join l in Entities.LocaInfo_Tab on a.LPDId equals l.LocaId
                           into tmpLocaInfo
                           let Loca = tmpLocaInfo.FirstOrDefault()
                           select new DocumentRelationModel
                           {
                               DRelationId = a.DRelationId,
                               ID = a.Type == 3 ? Dev.CompanySerial: a.LPDId,
                               PropertyName = a.Type == 2 ? "基站" : a.Type == 3 ? "设备" : "项目",
                               Name = a.Type == 2 ? Loca.LocaName : a.Type == 3 ? Dev.DeviceName : Pro.ProjectName,
                           };
                totalCount = linq.Count();
                List<DocumentRelationModel> list = linq.OrderBy(i => i.ID).Take(pagesize * pageindex).Skip(pagesize * (pageindex - 1)).ToList();

                JavaScriptSerializer jsonSerialize = new JavaScriptSerializer();
                strJson = jsonSerialize.Serialize(list);
            }
            var jsonResult = new { total = totalCount.ToString(), rows = strJson };
            return Content("{\"total\": " + totalCount.ToString() + ",\"rows\":" + strJson + "}");
        }

        /// <summary>
        /// 获取基站、设备、项目信息
        /// </summary>
        /// <returns></returns>
        public ActionResult GetResources()
        {
            //首先获取前台传递过来的参数
            int pageindex = Request["page"] == null ? 1 : Convert.ToInt32(Request["page"]);
            int pagesize = Request["rows"] == null ? 10 : Convert.ToInt32(Request["rows"]);

            string Name = Request["Name"] == null ? "" : Request["Name"].ToString();
            string ID = Request["ID"] == null ? "" : Request["ID"].ToString();
            int Type = Request["Type"] == null ? 1 : int.Parse(Request["Type"].ToString());
            string DocumentId = Request["DocumentId"];
            string strJson;
            int totalCount = 0;   //输出参数
            using (CYOADBEntities Entities = new CYOADBEntities())
            {
                int RType = 0;


                IEnumerable<ResourcesModel> model = null;
                List<ResourcesModel> list = new List<ResourcesModel>();
                //获取设备信息并排除已经添加进关系的设备
                if (Type == (int)ResourcesType.Dev)
                {
                    RType = (int)ResourcesType.Dev;
                    List<string> tmp = Entities.DocumentRelation_Tab.Where(i => i.DocumentId == DocumentId && i.Type == RType).Select(i => i.LPDId).ToList();
                    string DeviceIds = "";
                    foreach (string str in tmp)
                    {
                        DeviceIds += str + ",";
                    }
                    model = from a in Entities.DevInfo_Tab.Where(i => !DeviceIds.Contains(i.DeviceId))
                            select new ResourcesModel
                            {
                                ID = a.DeviceId,
                                Code = a.CompanySerial,
                                Name = a.DeviceName
                            };



                }
                //获取基站信息并排除已经添加进关系的基站
                if (Type == (int)ResourcesType.Loca)
                {
                    RType = (int)ResourcesType.Loca;
                    List<string> tmp = Entities.DocumentRelation_Tab.Where(i => i.DocumentId == DocumentId && i.Type == RType).Select(i => i.LPDId).ToList();
                    string LocaId = "";
                    foreach (string str in tmp)
                    {
                        LocaId += str + ",";
                    }
                    model = from a in Entities.LocaInfo_Tab.Where(i => !LocaId.Contains(i.LocaId))
                            select new ResourcesModel
                            {
                                ID = a.LocaId,
                                Code = a.LocaId,
                                Name = a.LocaName
                            };

                }
                //获取项目信息并排除已经添加进关系的项目
                if (Type == (int)ResourcesType.Pro)
                {
                    RType = (int)ResourcesType.Pro;
                    List<string> tmp = Entities.DocumentRelation_Tab.Where(i => i.DocumentId == DocumentId && i.Type == RType).Select(i => i.LPDId).ToList();
                    string ProjectId = "";
                    foreach (string str in tmp)
                    {
                        ProjectId += str + ",";
                    }
                    model = from a in Entities.ProInfo_Tab.Where(i => !ProjectId.Contains(i.ProjectId))
                            select new ResourcesModel
                            {
                                ID = a.ProjectId,
                                Code = a.ProjectId,
                                Name = a.ProjectName
                            };

                }



                //名称
                if (!string.IsNullOrEmpty(Name))
                {
                    model = model.Where(i => i.Name.Contains(Name));
                }

                //编号
                if (!string.IsNullOrEmpty(ID))
                {
                    model = model.Where(i => i.ID.Contains(ID));
                }

                totalCount = model.Count();
                list = model.OrderBy(i => i.ID).Take(pagesize * pageindex).Skip(pagesize * (pageindex - 1)).ToList();
                JavaScriptSerializer jsonSerialize = new JavaScriptSerializer();
                strJson = jsonSerialize.Serialize(list);
            }

            var jsonResult = new { total = totalCount.ToString(), rows = strJson };
            return Content("{\"total\": " + totalCount.ToString() + ",\"rows\":" + strJson + "}");
        }

        /// <summary>
        /// 添加资料关系信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ActionResult DocumentRelationInfoAdd(ResourcesModel model)
        {
            int code = 0;
            if (!string.IsNullOrEmpty(model.ResourcesJson))
            {
                JavaScriptSerializer jsonSerialize = new JavaScriptSerializer();
                List<TempModel> lis = jsonSerialize.Deserialize<List<TempModel>>(model.ResourcesJson);
                using (CYOADBEntities Entities = new CYOADBEntities())
                {
                    foreach (TempModel li in lis)
                    {
                        string newID = Guid.NewGuid().ToString();
                        DocumentRelation_Tab drt = new DocumentRelation_Tab();
                        drt.DRelationId = newID;
                        drt.DocumentId = model.ID;
                        drt.Type = li.Property;
                        drt.LPDId = li.ID;

                        Entities.DocumentRelation_Tab.Add(drt);
                        Entities.Entry<DocumentRelation_Tab>(drt).State = System.Data.Entity.EntityState.Added;
                    }
                    code = Entities.SaveChanges();
                }
            }
            if (code > 0)
            {
                return Content("{\"msg\":\"添加成功！\",\"success\":true}");
            }
            else
            {
                return Content("{\"msg\":\"添加失败！入库失败\",\"success\":false}");
            }
        }

        /// <summary>
        /// 根据ID删除资料关系信息
        /// </summary>
        /// <returns></returns>
        public ActionResult DocumentRelationDel()
        {
            string DocumentRelationID = Request["DocumentRelationID"] == null ? "1" : Request["DocumentRelationID"].ToString();
            int Code = 0;
            using (CYOADBEntities Entities = new CYOADBEntities())
            {
                DocumentRelation_Tab dt = Entities.DocumentRelation_Tab.Where(i => i.DRelationId == DocumentRelationID).FirstOrDefault();
                Entities.DocumentRelation_Tab.Add(dt);
                Entities.Entry<DocumentRelation_Tab>(dt).State = System.Data.Entity.EntityState.Deleted;
                Code = Entities.SaveChanges();
                if (Code > 0)
                {

                    return Content("{\"msg\":\"删除成功！\",\"success\":true}");
                }
                else
                {
                    return Content("{\"msg\":\"删除失败！\",\"success\":true}");
                }
            }
        }

        public JsonResult UploadFile()
        {
            //获取客户端上传的文件集合
            HttpFileCollection files = System.Web.HttpContext.Current.Request.Files;
            //获取文件集合中的第一个文件(每次只上传一个文件)
            HttpPostedFile file = files[0];
            using (CYOADBEntities Entities = new CYOADBEntities())
            {
                //判断文件是否上传过
                Document_Tab DocumentTab = Entities.Document_Tab.Where(i => i.Path.Contains(file.FileName)).FirstOrDefault();
                if (DocumentTab != null)
                {
                    ImageInfo insf = new ImageInfo();
                    insf.Path = "1";
                    return Json(insf);
                }
            }
            //int si = file.ContentLength;
            //if(si>15728640)
            //{
            //    return "3";
            //}
            ////上传文件后缀限制
            //string UploadExt = System.Configuration.ConfigurationManager.AppSettings["upload_ext"].ToString();
            //if (!UploadExt.Contains(System.IO.Path.GetExtension(file.FileName)))
            //{
            //    return "2";
            //}
            //定义文件存放的目标路径
            string targetDir = System.Web.HttpContext.Current.Server.MapPath("~/Files");
            string strURL = "http://" + System.Web.HttpContext.Current.Request.Url.Authority + "/Files/";
            ////组装新的文件名
            //TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            //string strFileName =Convert.ToInt64(ts.TotalSeconds).ToString() + System.IO.Path.GetExtension(file.FileName);
            //组合成文件的完整路径
            string path = System.IO.Path.Combine(targetDir, System.IO.Path.GetFileName(file.FileName));
            //组合成文件的网络路径
            string DownloadUrl = strURL + System.IO.Path.GetFileName(file.FileName);
            //保存上传的文件到指定路径中
            file.SaveAs(path);
            ImageInfo inf = new ImageInfo();
            inf.Path = path;
            inf.DownloadUrl = DownloadUrl;
            return Json(inf);
        }

        /// <summary>
        /// 通过Type(1 项目 2 设备 3 基站）来删除资料关系
        /// </summary>
        /// <param name="Type"></param>
        /// <param name="ID"></param>
        public void DelDocumentByID(string ID)
        {
            using (CYOADBEntities Entities = new CYOADBEntities())
            {
                List<DocumentRelation_Tab> list = Entities.DocumentRelation_Tab.Where(i => i.LPDId == ID).ToList();
                if (list.Count > 0)
                {
                    foreach (DocumentRelation_Tab DocumentRelationTab in list)
                    {
                        Entities.DocumentRelation_Tab.Add(DocumentRelationTab);
                        Entities.Entry<DocumentRelation_Tab>(DocumentRelationTab).State = System.Data.Entity.EntityState.Deleted;
                    }
                }
                Entities.SaveChanges();
            }
        }
    }
    public class ImageInfo
    {
        public string Path { set; get; }
        public string DownloadUrl { set; get; }
    }
}
